//
//  ConfirmOrderVC.m
//  sensen_ios
//
//  Created by pro on 16/2/27.
//  Copyright © 2016年 pro. All rights reserved.
//

#import "ConfirmOrderVC.h"

// 控制器
#import "ConfirmPayVC.h" // 确认支付
#import "ManageAddressVC.h" // 地址
#import "RubyVC.h" // 红包

// 单元格
#import "ConfirmOrderProductCell.h" // 确认订单中的商品单元格
#import "PayStyleCell.h" // 支付方式单元格
#import "ConfirmOrderNoAddressCell.h" // 没地址时候的单元格
#import "ConfirmOrderAddressCell.h" // 有地址时候的单元格

@interface ConfirmOrderVC () <UITableViewDataSource, UITableViewDelegate, ManageAddressSelectAddressDelegate, RubyDelegate>
{
    AddressModel *_addressModel; // 地址model
    RubyModel *_rubyModel; // 红包model
    NSString *_freight; // 运费
    NSString *_discount; // 店铺优惠
    CGFloat _totalPrice; // 支付总价

    NSArray *_titlesAry; // 左侧标题数组
}
@property (nonatomic, strong) UITableView *tableView; // 表视图

// 确认视图及其子视图
@property (nonatomic, strong) UIView *confirmView; // 结算视图
@property (nonatomic, strong) UIButton *confirmButton; // 结算按钮
@property (nonatomic, strong) UIActivityIndicatorView *activity; // 转动视图
@property (nonatomic, strong) UILabel *priceLabel; // 合计总价Label

@end

@implementation ConfirmOrderVC

#pragma mark - 视图方法
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"确认订单";
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self createLeftBarButtonItemWithImagename:nil]; // 创建左侧返回按钮
    
    [self _initLocalData]; // 初始化本地数据（标题数组等）
    [self _createViews]; // 创建视图
    [self _initData];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    
    // 设置背景颜色
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageWithColor:SS_NAVI_ORANGE_COLOR] forBarMetrics:UIBarMetricsDefault];
    
    // 隐藏标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main hideTabBar];
}
- (void)viewWillDisappear:(BOOL)animated {
    // 显示标签栏
    MainTabBarController *main = (MainTabBarController *)self.navigationController.tabBarController;
    [main showTabBar];
}


#pragma mark - 获取数据
// 获取本地数据
- (void)_initLocalData {

    // 初始化本地数据
    _titlesAry = @[@"配送费用:", @"店铺优惠:", @"优惠选择:", @"买家留言:"];
}
- (void)_initData {

    // 获取默认地址
    [BoyeHttpClient post:@"BY_Address_getDefaultAddress" apiVerson:100 params:@{@"uid":[CommonCache getUserInfo].uid} success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"默认地址:%@", result);
        // 如果返回0，则说明没有默认地址
        if ([result integerValue] == 0) {
            _addressModel = nil;
            [SVProgressHUD showErrorWithStatus:@"没有默认地址,请添加地址" withDuration:2];
            return;
        }
        // 返回的不是0，则根据获得某个地址的接口获得地址
        [BoyeHttpClient post:@"BY_Address_getInfo" apiVerson:100 params:@{@"id":result, @"uid":[CommonCache getUserInfo].uid} success:^(AFHTTPRequestOperation *operation, id result) {
            // 获得地址刷新表视图
            _addressModel = [[AddressModel alloc] initContentWithDic:(NSDictionary *)result];
            
            // 根据地址id来获得总运费
            [self _countFreight];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
        }];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:error.domain withDuration:2];
    }];
    
}


#pragma mark - 创建视图
- (void)_createViews {
    
    [self _createConfirmView];
    [self _initTableView]; // 创建表视图
    
}
// 创建确认视图
- (void)_createConfirmView {
    // 结算视图
    _confirmView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 49)];
    _confirmView.bottom = SCREEN_HEIGHT - 64;
    [self.view addSubview:_confirmView];
    
    // 子视图
    CGFloat x, y, width, height;
    width = 80;
    height = _confirmView.height;
    y = 0;
    x = _confirmView.width - width;
    // 1.结算按钮
    _confirmButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _confirmButton.frame = CGRectMake(x, y, width, height);
    _confirmButton.backgroundColor = SS_NAVI_ORANGE_COLOR;
    [_confirmButton setTitle:@"确认" forState:UIControlStateNormal];
    [_confirmButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_confirmButton addTarget:self action:@selector(_confirmAction:) forControlEvents:UIControlEventTouchUpInside];
    [_confirmView addSubview:_confirmButton];
    
    // 刚开始设置按钮不能点击
    _confirmButton.enabled = NO;
    _confirmButton.backgroundColor = [UIColor colorWithWhite:0.85 alpha:1];
    
    
    // 菊花转动
    _activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activity.frame = _confirmButton.frame;
    [_confirmView addSubview:_activity];
    _activity.hidesWhenStopped = YES;
    [_activity startAnimating];

    
    // 2.价格Label
    y = 5;
    width = 120;
    height = 20;
    _priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(x, y, width, height)];
    _priceLabel.font = FONT(15);
    _priceLabel.text = @"合计：￥0.00";
    _priceLabel.textColor = [UIColor darkGrayColor];
    _priceLabel.textAlignment = NSTextAlignmentRight;
    [_confirmView addSubview:_priceLabel];
    _priceLabel.right = _confirmButton.left - 10;
    _priceLabel.center = CGPointMake(_priceLabel.center.x, _confirmView.height / 2);
}


// 创建表视图
- (void)_initTableView {
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - _confirmView.height) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    // 注册单元格
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CartCell"];
    [_tableView registerClass:[ConfirmOrderProductCell class] forCellReuseIdentifier:@"ProductCell"];
    [_tableView registerClass:[ConfirmOrderAddressCell class] forCellReuseIdentifier:@"ConfirmOrderAddressCell"];
    [_tableView registerClass:[ConfirmOrderNoAddressCell class] forCellReuseIdentifier:@"ConfirmOrderNoAddressCell"];

}



#pragma mark - UITableViewDataSource UITableViewDelegate
// 设置组数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
// 设置行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return _titlesAry.count + _itemsAry.count;
    } else {
        return 2;
    }
}
// 设置单元格属性
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 通用单元格
    UITableViewCell *normalCell = [tableView dequeueReusableCellWithIdentifier:@"normalCell"];
    if (normalCell == nil) {
        normalCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"normalCell"];
        normalCell.textLabel.textColor = [UIColor darkGrayColor];
        normalCell.textLabel.font = FONT(14);

        normalCell.detailTextLabel.textColor = SS_NAVI_ORANGE_LIGHT_COLOR;
        normalCell.detailTextLabel.font = FONT(14);
    }
    
    // 第一组
    if (indexPath.section == 0) {
        if (_addressModel != nil) { // 有地址model
            ConfirmOrderAddressCell *addressCell = (ConfirmOrderAddressCell *)[tableView dequeueReusableCellWithIdentifier:@"ConfirmOrderAddressCell"];
            addressCell.model = _addressModel;
            return addressCell;
        } else { // 没地址model
            ConfirmOrderNoAddressCell *noAddressCell = (ConfirmOrderNoAddressCell *)[tableView dequeueReusableCellWithIdentifier:@"ConfirmOrderNoAddressCell"];
            return noAddressCell;
        }
    }
    
    // 第二组
    else if (indexPath.section == 1) {
        if (indexPath.row < _itemsAry.count) {
            ConfirmOrderProductCell *productCell = (ConfirmOrderProductCell *)[tableView dequeueReusableCellWithIdentifier:@"ProductCell"];
            productCell.model = _itemsAry[indexPath.row];
            return productCell;
        } else {
            // 配送方式
            if (indexPath.row == _itemsAry.count) {
                normalCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                normalCell.textLabel.text = _titlesAry[0];
                if (_freight != nil) { // 已经计算运费
                    if ([_freight isEqualToString:@"-1"]) {
                        normalCell.detailTextLabel.text = @"包邮";
                    } else {
                        normalCell.detailTextLabel.text = [NSString stringWithFormat:@"￥%@", _freight];
                    }
                }
                return normalCell;
            }
            // 店铺优惠
            else if (indexPath.row == _itemsAry.count + 1) {
                normalCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                if (_discount != nil) {
                    normalCell.detailTextLabel.text = [NSString stringWithFormat:@"- ￥%@", _discount];
                } else {
                    normalCell.detailTextLabel.text = @"无优惠";
                }
                normalCell.textLabel.text = _titlesAry[1];
                return normalCell;
            }
            // 优惠选择
            else if (indexPath.row == _itemsAry.count + 2) {
                normalCell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                if (_rubyModel != nil) {
                    normalCell.detailTextLabel.text = [NSString stringWithFormat:@"- ￥%@", _rubyModel.money];
                }
                normalCell.textLabel.text = _titlesAry[2];
                return normalCell;
            }
            // 买家留言
            else {
                UITableViewCell *notesCell = [tableView dequeueReusableCellWithIdentifier:@"notesCell"];
                if (notesCell == nil) {
                    notesCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"notesCell"];
                    notesCell.tag = 100;
                    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 0, 70, notesCell.height)];
                    titleLabel.userInteractionEnabled = YES;
                    titleLabel.font = FONT(14);
                    titleLabel.text = _titlesAry[3];
                    titleLabel.textColor = [UIColor darkGrayColor];
                    titleLabel.textAlignment = NSTextAlignmentLeft;
                    [notesCell addSubview:titleLabel];
                    
                    UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(titleLabel.right, 10, SCREEN_WIDTH - titleLabel.right - 20, notesCell.height - 20)];
                    NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:@"选填,可填写您与卖家达成一致的要求"];
                    [attr addAttribute:NSFontAttributeName value:FONT(14) range:NSMakeRange(0, attr.string.length)];
                    tf.attributedPlaceholder = attr;
                    tf.textColor = [UIColor darkGrayColor];
                    tf.font = FONT(14);
                    tf.tag = 1000;
                    [notesCell addSubview:tf];
                }
                return notesCell;
            }
            
        }
    }
    
    else {
        return nil;
    }
}
// 设置单元格行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return _addressModel != nil ? 60 : 44;
    }
    else if (indexPath.section == 1) {
        if (indexPath.row < _itemsAry.count) {
            return 80;
        } else {
            return 44;
        }
    }
    else {
        return 44;
    }
}
// 设置组头高
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else {
        return 5;
    }
}
// 组头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
// 组尾高度
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5;
}
// 组尾视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
// 单元格点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO]; // 取消选中阴影
    
    // 地址选择页面
    if (indexPath.section == 0) {
        ManageAddressVC *vc = [[ManageAddressVC alloc] init];
        vc.delegate = self;
        [self.navigationController pushViewController:vc animated:YES];
    }
    // 第二组
    else {
        // 商铺优惠
        if (indexPath.row == _itemsAry.count + 1) {
            if (_discount == nil) {
                [SVProgressHUD showOnlyStatus:@"当前无商铺优惠\n或您购买的商品不满足优惠条件!" withDuration:3];
            } else {
                [SVProgressHUD showOnlyStatus:[NSString stringWithFormat:@"满%@减%@!", _discountModel.condition, _discountModel.discount_money] withDuration:3];
            }
        }
        // 优惠选择
        if (indexPath.row == _itemsAry.count + 2) {
            RubyVC *vc = [[RubyVC alloc] init];
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
        }
    }
}



#pragma mark - 地址选择代理
- (void)didSelectAddress:(AddressModel *)model {
    _addressModel = model;
    
    // 计算运费，并刷新视图都在里面了
    [self _countFreight];

}
#pragma mark - 红包选择代理
- (void)rubyDidChoose:(RubyModel *)model {
    _rubyModel = model;
    // 判断商品总价是否大于使用限制，若小于，则不能使用该红包
    CGFloat totalPrice = 0;
    // 计算商品总价
    for (CartProductModel *model in _itemsAry) {
        totalPrice += [model.price floatValue] * [model.count integerValue];
    }
    if (totalPrice < [model.use_condition floatValue]) {
        
        _rubyModel = nil;
        
        [SVProgressHUD showErrorWithStatus:@"你的商品价格小于红包最低使用价格，请重新选择红包" withDuration:2];
        return;
    }
    
    // 计算总价
    [self _countTotalPrice];
    // 刷新表视图
    [_tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationFade];
}

#pragma mark - 键盘
- (void)keyboardFrameChange:(NSNotification *)notification {
    [super keyboardFrameChange:notification];
    [UIView animateWithDuration:0.25 animations:^{
        // 获取键盘的frame
        NSValue *boundsValue = [notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect frame = [boundsValue CGRectValue];
        
        // 键盘y值，是对于手机屏幕的，所以没上升的时候是屏幕高度
        CGFloat y = frame.origin.y;
        // 键盘上升
        if (y < SCREEN_HEIGHT) {
            // 算键盘的frame的时候，不能算导航栏的，是相对于屏幕的
            _tableView.height = y - 64 - 30; // 30是（完成视图）的高度
        }
        // 键盘下降
        else {
            _tableView.height = SCREEN_HEIGHT - 64 - _confirmView.height;
        }
    }];
}




#pragma mark - 点击事件
- (void)_confirmAction:(UIButton *)button {
    
    // 点击确认就添加订单了
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:[CommonCache getUserInfo].uid forKey:@"uid"];
    NSMutableArray *ary = [[NSMutableArray alloc] init];
    for (CartProductModel *model in _itemsAry) {
        [ary addObject:model._id];
    }
    // 购物车id数组
    NSString *cart_ids = [ary componentsJoinedByString:@","];
    [params setObject:cart_ids forKey:@"cart_ids"];
    
    // 地址
    [params setObject:@(_addressModel.address_id) forKey:@"address_id"];
    if (_rubyModel != nil) {
        [params setObject:_rubyModel.ruby_id forKey:@"idcode"];
    }
    // 备注
    UITableViewCell *notesCell = (UITableViewCell *)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:4 inSection:1]];
    UITextField *tf = (UITextField *)[notesCell viewWithTag:1000];
    if (tf.text != nil) {
        [params setObject:tf.text forKey:@"note"];
    }
    
    [params setObject:@3 forKey:@"from"];
    
    [SVProgressHUD showWithStatus:@"正在为您添加订单..."];
    [BoyeHttpClient post:@"BY_Orders_add" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        
        [SVProgressHUD dismiss];
        
        // 创建支付订单model
        PayOrderModel *payOrderModel = [[PayOrderModel alloc] initContentWithDic:result];
        
        // 添加订单成功后，跳转到选择支付页面
        ConfirmPayVC *vc = [[ConfirmPayVC alloc] init];
        vc.payOrderModel = payOrderModel;
        
        [self.navigationController pushViewController:vc animated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.domain withDuration:1];
    }];
    
    
}




#pragma mark - 其他方法（简单代码块）
#pragma mark -- 计算运费 --
- (void)_countFreight {
    CGFloat totalPrice = 0;
    // 计算商品总价
    for (CartProductModel *model in _itemsAry) {
        totalPrice += [model.price floatValue] * [model.count integerValue];
    }
    
    // 如果商品总价大于满减要求，则设置满减金额
    if (totalPrice >= [_discountModel.condition floatValue]) {
        _discount = _discountModel.discount_money; // 设置优惠金额
        
        // 如果又是满减包邮的，则包邮
        if ([_discountModel.free_shipping integerValue] != 0) {
            _freight = @"-1"; // 包邮的话，设置邮费为-1
            // 刷新表视图
            [_tableView reloadData];
            [self _countTotalPrice];
        }
        else {
            [self _requestFreight];
        }
    }
    else {
        [self _requestFreight];
    }
   
}
// 请求运费
- (void)_requestFreight {
    // 购物车id
    NSMutableArray *cartIds = [NSMutableArray array];
    for (CartProductModel *model in _itemsAry) {
        [cartIds addObject:model._id];
    }
    NSDictionary *params = @{@"cart_ids":[cartIds componentsJoinedByString:@","],
                             @"address_id":@(_addressModel.address_id),
                             @"uid":[CommonCache getUserInfo].uid};
    NSLog(@"%@",params);
    // 根据地址id来获得总运费
    [BoyeHttpClient post:@"BY_Freight_cost" apiVerson:100 params:params success:^(AFHTTPRequestOperation *operation, id result) {
        NSLog(@"%@", result);
        // 设置运费
        _freight = [NSString stringWithFormat:@"%@", result];
        
        // 刷新表视图
        [_tableView reloadData];
        
        [self _countTotalPrice];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"未知错误，请联系客服" withDuration:1];
    }];

}
#pragma mark -- 计算总价，并设置确认按钮可点击 --
- (void)_countTotalPrice {
    CGFloat totalPrice = 0;
    // 计算商品总价
    for (CartProductModel *model in _itemsAry) {
        totalPrice += [model.price floatValue] * [model.count integerValue];
    }
    
    // 减去店铺优惠
    totalPrice -= [_discount floatValue];

    // 减去优惠费用
    totalPrice -= [_rubyModel.money floatValue];
    
    
    
    // 添加配送费用
    if ([_freight floatValue] > 0) {
        totalPrice += [_freight floatValue];
    }
    
    
    if (totalPrice <= 0) {
        totalPrice = 0.01;
    }

    
    // 改变价格
    //一 创建NSMutableAttributedString 对象
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:_priceLabel.text];
    // 字体颜色
    [attrString addAttribute:NSForegroundColorAttributeName
                       value:[UIColor darkGrayColor]
                       range:[_priceLabel.text rangeOfString:@"合计："]];
    // 字体
    [attrString addAttribute:NSFontAttributeName
                       value:[UIFont systemFontOfSize:15]
                       range:[_priceLabel.text rangeOfString:@"合计："]];
    _priceLabel.attributedText = attrString;
    _priceLabel.text = [NSString stringWithFormat:@"总计(含运费):￥%.2lf", totalPrice];
    _priceLabel.width = [_priceLabel.text getSizeOfString:15].width;
    _priceLabel.right = _confirmButton.left - 10;

    // 设置菊花停止转动，并设置确认按钮可点击
    [_activity stopAnimating];
    _confirmButton.enabled = YES;
    _confirmButton.backgroundColor = SS_NAVI_ORANGE_COLOR;
}


#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}




@end
